package com.mallbook.controller.filter;

import com.mallbook.model.pojo.User;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-07-08
 */
@WebFilter({"/order", "/alipay", "/cart","/ucenter"})
public class FrontFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(FrontFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        logger.info("进入FrontFilter过滤器");
        HttpServletRequest req = (HttpServletRequest) request;
        logger.info("URL:" + req.getRequestURL());
        logger.info("QS:" + req.getQueryString());
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("USER");
        if (user == null) {
            System.out.println(req.getHeader("ajax") );
            if (req.getHeader("ajax") != null||req.getHeader("X-Requested-With")!= null) {
                logger.info("该请求是 AJAX 异步HTTP请求");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("msg", "302");
                PrintWriter writer = resp.getWriter();
                writer.print(jsonObject);
                writer.close();
            } else {
                logger.info("该请求不是 AJAX 异步HTTP请求");
                resp.sendRedirect("user?opr=login"); // 转到登录界面
            }
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
    }

}
